﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI.WebControls;

namespace OnlineCellphoneStore
{
    public partial class Login : System.Web.UI.Page
    {
        List<string> SecurityQuestionAnswer = new List<string>();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.QueryString.Count > 0 && Request.QueryString["WriteSecurityQuestion"] == "true")
            {
                try
                {
                    loginMain.Attributes.CssStyle.Value = "display: none;";
                    loginQuestionDisplay.Attributes.CssStyle.Value = "display: inline;";
                    string UserName = Request.QueryString["UserName"].ToString();
                    SecurityQuestionAnswer = SQLAdapter.GetSecurityQuestionAnswer(UserName);
                    tdSQ.InnerHtml = SecurityQuestionAnswer[0];
                }
                catch (Exception ex)
                {
                    Response.Write(ex.Message);

                }
            }
        }
        protected void btnSignin_Click(object sender, EventArgs e)
        {
            SiteResponseToLoginRequest();
        }
        protected void BtnConfirmAns_Click(object sender, EventArgs e)
        {
            if (CustomValidator_txtAnsInput.IsValid == true && txtAnsInput.Value.Length > 0)
            {
                try
                {
                    string UserName = Request.QueryString["UserName"].ToString();
                    string Password = SQLAdapter.GetPassword(UserName);
                    lblPassword.InnerHtml = Password;
                    BtnConfirmAns.Enabled = false;
                    tdBackToLogin.Attributes.CssStyle.Value = "display: inline;";
                    tdPassword.Attributes.CssStyle.Value = "display: inline;";
                }
                catch (Exception ex)
                {
                    Response.Write(ex.Message);
                }
            }
        }
        protected void btnUsernameAuth_Click(object sender, EventArgs e)
        {
            SiteResponseToUserNameAuthentication();
        }
        protected void CustomValidator_txtAnsInput_ServerValidate(object source, ServerValidateEventArgs args)
        {
            string UserAnswer = args.Value;
            string CurrectAnswer = SecurityQuestionAnswer.ElementAt(1);
            if (String.Compare(UserAnswer, CurrectAnswer) == 0)
            {
                args.IsValid = true;
            }
            else
            {
                args.IsValid = false;
            }
        }
        protected void btnBackToLogin_Click(object sender, EventArgs e)
        {
            Response.Redirect("Login.aspx", false);
        }
        private void SiteResponseToLoginRequest()
        {
            try
            {
                string UserName = txtSubmitUser.Value;
                string Password = txtSubmitPass.Value;
                int ClientID = SQLAdapter.VerifyUser(UserName, Password);
                if (ClientID != -1)
                {
                    // Add Cookies
                    AddCookies(ClientID.ToString());
                    // Redirect to the home page
                    string Url = "../Main.aspx?ClientID=" + ClientID;
                    Response.Redirect(Url, false);
                }
                else
                {
                    divErrorCredentials.Attributes.CssStyle.Value = "display: block;";
                }
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
            }
        }
        private void SiteResponseToUserNameAuthentication()
        {
            try
            {
                string UserName = txtUserAuth.Value;
                int ClientID = SQLAdapter.CheckIfUserNameExists(UserName);
                if (ClientID != -1)
                {
                    Response.Redirect("Login.aspx?WriteSecurityQuestion=true&UserName=" + UserName, false);
                }
                else
                {
                    StringBuilder sb = new StringBuilder();
                    sb.Append("<script>");
                    sb.Append("alert('The UserName does not exists in the system.')");
                    sb.Append("</script>");
                    ClientScript.RegisterClientScriptBlock(GetType(), "alert", sb.ToString());
                }
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
            }
        }
        private void AddCookies(string ClientID)
        {
            HttpCookie IDCookie = new HttpCookie("ClientID", ClientID);
            HttpCookie TimeCookie = new HttpCookie("LastVisit", DateTime.Now.ToString());
            IDCookie.Expires = DateTime.Now.AddDays(30);
            TimeCookie.Expires = DateTime.Now.AddDays(30);
            Response.Cookies.Add(IDCookie);
            Response.Cookies.Add(TimeCookie);
        }
    }
}